import time
from threading import Thread, Lock, RLock

# mutexA = Lock()
# mutexB = Lock()
#
#
# # 死锁
# class MyTread(Thread):
#     def run(self) -> None:
#         self.func1()
#         self.func2()
#
#     def func1(self):
#         mutexA.acquire()
#         print(f'{self.name} 抢到A锁')
#         mutexB.acquire()
#         print(f'{self.name} 抢到B锁')
#         mutexB.release()
#         mutexA.release()
#
#     def func2(self):
#         mutexB.acquire()
#         print(f'{self.name} 抢到B锁')
#         time.sleep(2)
#         mutexA.acquire()
#         print(f'{self.name} 抢到A锁')
#         mutexA.release()
#         mutexB.release()
#
#
# if __name__ == '__main__':
#     for i in range(10):
#         t = MyTread()
#         t.start()
# # 当线程需要2个锁时，线程1拿到A锁，线程2拿到b锁就死锁了


# 递归锁 可以连续acquire和release,引用技术为0才能公共抢
# 每次acquire引用计数+1
# 每次release引用计数-1
mutexA = mutexB = RLock()


class MyTread(Thread):
    def run(self) -> None:
        self.func1()
        self.func2()

    def func1(self):
        mutexA.acquire()
        print(f'{self.name} 抢到A锁')
        mutexB.acquire()
        print(f'{self.name} 抢到B锁')
        mutexB.release()
        mutexA.release()

    def func2(self):
        mutexB.acquire()
        print(f'{self.name} 抢到B锁')
        time.sleep(2)
        mutexA.acquire()
        print(f'{self.name} 抢到A锁')
        mutexA.release()
        mutexB.release()


if __name__ == '__main__':
    for i in range(10):
        t = MyTread()
        t.start()
